//
//  CYNetWorkPostFileRequest.m
//  TestNetWorkDemo
//
//  Created by lc4y on 2018/2/23.
//  Copyright © 2018年 lc4y. All rights reserved.
//

#import "CYNetWorkPostFileRequest.h"
#import "CYNetworkCommonArguments.h"
#import <AFNetworking.h>

@interface CYNetWorkPostFileRequest ()

@property (nonatomic, copy)   NSString *url;
@property (nonatomic, strong) NSDictionary *arguments;
@property (nonatomic, strong) NSData *fileData;
@property (nonatomic, strong) NSString *fileType;
@property (nonatomic, strong) NSString *name;
@end

@implementation CYNetWorkPostFileRequest

+ (void)CYNetPostFileRequetWithURL:(NSString *)url params:(NSDictionary *)params fileData:(NSData *)fData fileType:(NSString *)fType name:(NSString *)serverName complete:(void (^)(id obj,NSError *error))completion {
    CYNetWorkPostFileRequest *postFileRequet = [[CYNetWorkPostFileRequest alloc] init];
    postFileRequet.url       = url;
    postFileRequet.arguments = params;
    postFileRequet.fileData  = fData;
    postFileRequet.fileType  = fType;
    postFileRequet.name      = serverName;
    
    [postFileRequet startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        completion(request.responseObject,nil);
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        completion(nil,request.error);
    }];
}

- (YTKRequestMethod)requestMethod {
    return YTKRequestMethodPOST;
}

- (NSString *)requestUrl {
    return self.url;
}

- (NSDictionary *)requestArgument {
    NSDictionary *commonDict = [CYNetworkCommonArguments shareCommonArguments].commonArguments ? [CYNetworkCommonArguments shareCommonArguments].commonArguments : @{};
    NSMutableDictionary *finalDict = [NSMutableDictionary dictionaryWithDictionary:commonDict];
    [finalDict addEntriesFromDictionary:self.arguments];
    
    if([CYNetworkCommonArguments shareCommonArguments].delegate && [[CYNetworkCommonArguments shareCommonArguments].delegate respondsToSelector:@selector(CYNetworkFetchCommonArgumensts:)]) {
        return [[CYNetworkCommonArguments shareCommonArguments].delegate CYNetworkFetchCommonArgumensts:finalDict];
    }
    
    return finalDict;
}

- (AFConstructingBlock)constructingBodyBlock {
    __weak typeof(self) weakSelf = self;
    return ^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:weakSelf.fileData name:weakSelf.name fileName:[NSString stringWithFormat:@"fileImage%d",arc4random() % 10000] mimeType:weakSelf.fileType];
    };
}

@end
